package com.jar.exercise.多线程.Semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Main implements Runnable {

	Semaphore semaphore = new Semaphore(6);

	public static void main(String[] args) throws InterruptedException {
		Main main = new Main();
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 6; i++) {
			TimeUnit.MILLISECONDS.sleep(2000);
			executorService.execute(main);
		}
		executorService.shutdown();
	}

	@Override
	public void run() {
		try {
			//请求获得许可，如果有可获得的许可则继续往下执行，许可数减1。否则进入阻塞状态
			semaphore.acquire();
			System.out.printf(
					"线程%s进入,当前已有%d个并发,可用信号%d\n",
					Thread.currentThread().getName(),
					6 - semaphore.availablePermits(),
					semaphore.availablePermits()
			);
			Thread.sleep((long) (Math.random() * 10000));
			semaphore.release();
			System.out.printf(
					"线程%s离开,当前已有%d个并发,可用信号%d\n",
					Thread.currentThread().getName(),
					6 - semaphore.availablePermits(),
					semaphore.availablePermits()
			);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
